package socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    // 服务器的 IP 和 服务器的端口
    public UdpEchoClient(String ip, int port) throws SocketException {
        serverIp = ip;
        serverPort = port;
        // 这个 new 操作, 就不再指定端口了. 让系统自动分配一个空闲端口
        socket = new DatagramSocket();
    }

    // 让这个客户端反复地从控制台读取用户输入的内容. 把这个内容构造成 UDP 请求, 发给服务器
    // 最终再显示在客户端的屏幕上.
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动!");
        while (true) {
            // 1. 从控制台读取用户输入的内容
            System.out.print("-> "); // 命令提示符, 提示用户要输入字符串
            String request = scanner.nextLine(); // 使用 nextLine() 读取整行输入

            // 2. 构造请求对象, 并发送给服务器
            byte[] sendData = request.getBytes();
            InetAddress serverAddress = InetAddress.getByName(serverIp);
            DatagramPacket requestPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
            socket.send(requestPacket);

            // 3. 读取服务器的响应, 并解析出响应内容
            byte[] receiveData = new byte[4096];
            DatagramPacket responsePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());

            // 4. 显示到屏幕上
            System.out.println("服务器响应: " + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        // UdpEchoClient client = new UdpEchoClient("42.192.83.143", 9090);
        client.start();
        client.start();
    }
}